// login && register
const express = require('express')
const router = express.Router()
const Jwt = require('../plugins/jwt')
const jsencrypt = require('../plugins/rsaEncrypt')
const multer = require('multer');
const Users = require('../Schemas/UserSchema') // user集合
const NewPhoneSmscode = require('../Schemas/NewUserPhone') // 存储新用户的验证码
const fs = require('fs')
const path = require('path');
const dirPath = path.join(__dirname, '..', 'public/HP')

// node-rsa 密码解密
const NodeRSA = require("node-rsa");
const key = new NodeRSA({ b: 1024 });
key.setOptions({ encryptionScheme: 'pkcs1' });
// 必须加上，加密方式问题。
//publicKey(GET)，用于获取公钥，只需要调用下内置的方法就行了，
router.get('/publicKey', (req, res) => {
    var publicDer = key.exportKey('public');
    var privateDer = key.exportKey('private');
    console.log('公钥:', publicDer);
    console.log('私钥:', privateDer);
})

//判断用户名， post
//api/user/Isun
//public
router.post('/Isun', (req, res) => {
    Users.findOne({ username: req.body.username }).then((user) => {
        if (user) {
            return res.json({ data: { code: 202, msg: "该昵称已存在" } })
        } else {
            return res.json({
                data: { code: 201, msg: "昵称可用" }
            })
        }
    })
})
//验证手机号是否注册
router.post('/IsPhone', (req, res) => {
    Users.findOne({ phone: req.body.phone }).then(user => {
        if (user) {
            return res.json({ data: { code: 202, msg: "该电话号码已被注册" } })
        } else {
            return res.json({ data: { code: 200, msg: "电话号码可用" } })
        }
    })
})
//存储注册时手机的验证码
router.post('/newphonesmscode', (req, res) => {
    var smscode = ('000000' + Math.floor(Math.random() * 999999)).slice(-6);
    let newuserp = req.body
    newuserp.smscode = smscode
    NewPhoneSmscode.findOne({ phone: req.body.phone }).then(n => {
        if (n) {
            NewPhoneSmscode.updateOne({ phone: req.body.phone }, {
                $set: {
                    smscode: smscode,
                    sendtime: req.body.sendtime
                }
            }).then(() => {
                let nps = newuserp
                res.json({ data: { code: 200, msg: '保存成功', nps } })
            })
                .catch(err => {
                    res.json({ data: { code: 500, msg: "注册失败", err } })
                })
        }
        else {
            const NPS = new NewPhoneSmscode(newuserp)
            NPS.save().then(nps => { res.json({ data: { code: 200, msg: '保存成功', nps } }) })
                .catch(err => {
                    res.json({ data: { code: 500, msg: "注册失败", err } })
                })
        }
    })

})
//验证注册验证码
router.post('/IdentifyNPS', (req, res) => {
    NewPhoneSmscode.findOne({ phone: req.body.phone }).then(user => {
        if (!user) {
            res.json({ data: { code: 502, message: "手机号错误", } })
        } else {
            if ((req.body.nowtime - user.sendtime) / 1000 > 60) {
                res.json({ data: { code: 501, message: "验证码已过期" } })
            } else {
                if (req.body.smscode == user.smscode) {
                    res.json({ data: { code: 200, message: "验证码有效", } })
                } else {
                    res.json({ data: { code: 500, message: "错误的验证码" } })
                }
            }
        }
    })

})
// 注册 请求会带数据 POST请求
// api/user/register
// public
router.post('/register', (req, res) => {
    let user = req.body
    user.password = jsencrypt.decrypt(req.body.password)
    const NewUser = new Users(user)
    NewUser.useraccount = "weiyun_" + req.body.phone + "_01"
    NewUser.save()
        .then(user => res.json({ data: { code: 200, msg: '注册成功', user } }))
        .catch(err => res.json({ data: { code: 500, msg: "注册失败", err } }))

})

// 登录 请求会带数据 POST请求
// 返回token, jwt passport
//public
// api/user/login
router.post('/login', (req, res) => {
    let password = jsencrypt.decrypt(req.body.password)
    let account = req.body.account;
    let reg = /^[a-zA-z](?!^[\d]+$)(?!^[-]+$)(?!^[_]+$)(?!^[a-zA-Z]+$)[\w-]{6,30}$/
    if (reg.test(account)) {
        Users.findOne({ useraccount: account })
            .then((user) => {
                if (!user) {
                    return res.json({ data: { code: 500, msg: '用户名或密码错误' } })
                }
                let userInfo = {
                }
                userInfo._id = user._id
                userInfo.logoUrl = user.logoUrl
                userInfo.username = user.username
                if (password == user.password) {
                    let jwt = new Jwt((user._id).toString())
                    let token = jwt.generateToken()
                    return res.json({ data: { code: 200, msg: "登陆成功", token, userInfo } })
                } else {
                    return res.json({ data: { code: 500, msg: '用户名或密码错误' } })
                }

            })
    } else {
        Users.findOne({ phone: account })
            .then((user) => {
                if (!user) {
                    return res.json({ data: { code: 500, msg: '用户名或密码错误' } })
                }
                let userInfo = {
                }
                userInfo._id = user._id
                userInfo.logoUrl = user.logoUrl
                userInfo.username = user.username
                if (password == user.password) {
                    let jwt = new Jwt((user._id).toString())
                    let token = jwt.generateToken()
                    return res.json({ data: { code: 200, msg: "登陆成功", token, userInfo } })
                } else {
                    return res.json({ data: { code: 500, msg: '用户名或密码错误' } })
                }

            })
    }

    userInfo = ""

})
//获取用户信息
router.post('/getUserInfo', (req, res) => {
    Users.findOne({ _id: req.body.userid }).then(user => {
        res.json({
            data: {
                code: 200,
                user
            }
        })
    }).catch(err => {
        res.json({
            data: {
                code: 500,
                message: "获取失败"
            }
        })
    })
})
//更新用户信息
router.post('/updateUserInfo', (req, res) => {
    Users.updateOne({ _id: req.body._id }, {
        $set: {
            username: req.body.username,
            sex: req.body.sex,
            age: req.body.age
        }
    }).then(() => {
        res.json({ data: { code: 200, message: "更新成功", } })
    }).catch(() => {
        res.json({ data: { code: 500, message: "更新失败" } })
    });
}
)
//更新用户账户
router.post('/updateUserAccount', (req, res) => {
    Users.updateOne({ _id: req.body._id }, {
        $set: {
            useraccount: req.body.account
        }
    }).then(() => {
        res.json({ data: { code: 200, message: "更新成功", } })
    }).catch(() => {
        res.json({ data: { code: 500, message: "更新失败" } })
    });
}
)

//配置图片存储地址
var stroage = multer.diskStorage({
    //设置上传的文件夹
    destination: function (req, file, cd) {
        cd(null, './public/HP')  // 注意是根目录 ，根目录，根目录
    },
    filename: function (req, file, cb) {
        //设置图片的名称
        cb(null, `${Date.now()}${Math.random().toString(36).slice(-6)}-${file.originalname}`)
    }
})
var upload = multer({ storage: stroage });
router.post('/upload', upload.any(), (req, res, next) => {
    let url = `http://${req.headers.host}/HP/${req.files[0].filename}`
    if (!req.files) {
        res.json({
            code: 201,
            message: '上传失败'
        })
    } else {
        Users.updateOne({
            _id: req.body.userInfoID
        }, {
            $set: {
                logoUrl: url,
            }
        }).then(() => {
            let name = req.body.userInfoLogoUrl.split('/')[4]
            console.log(name);
            if (name != 'IU.jpg') {
                fs.unlink(path.join(dirPath, name), (err) => {
                    if (err) {
                        res.json({ data: { code: 500, message: "更新失败" } })
                    }
                })
            }
            res.json({
                data: {
                    code: 200,
                    message: '上传成功',
                    url: url
                }
            })
            name = ""
        }).catch((err) => {
            console.log(err);
            res.json({ data: { code: 500, message: "更新失败" } })
        })
    }
})
//生成验证码
var createSmscode = (req, res) => {
    var smscode = ('000000' + Math.floor(Math.random() * 999999)).slice(-6);
    Users.updateOne({ _id: req.body._id }, {
        $set: {
            sendtime: req.body.sendtime,
            smscode: smscode
        },
    }).then(() => {
        res.json({ data: { code: 200, message: "获取验证码成功", smscode } })
    }).catch(() => {
        res.json({ data: { code: 500, message: "获取验证码失败", } })
    })
}
//验证手机号
router.post('/IdentifyPhone', (req, res) => {
    Users.findOne({ phone: req.body.phone }).then(user => {
        if (!user) {
            res.json({ data: { code: 502, message: "手机号错误", } })
        }
        else {
            createSmscode(req, res)
        }
    })

})
//验证验证码
router.post('/IdentifySmscode', (req, res) => {
    console.log(req.body);
    Users.findOne({ phone: req.body.phone }).then(user => {
        if (!user) {
            res.json({ data: { code: 502, message: "手机号错误", } })
        } else {
            if ((req.body.nowtime - user.sendtime) / 1000 > 60) {
                res.json({ data: { code: 501, message: "验证码已过期" } })
            } else {
                if (req.body.smscode == user.smscode) {
                    res.json({ data: { code: 200, message: "验证码有效", } })
                } else {
                    res.json({ data: { code: 500, message: "错误的验证码" } })
                }
            }

        }
    })
})
//验证新手机号
router.post('/IdentifyNewPhone', (req, res) => {
    Users.findOne({ _id: req.body._id }).then(user => {
        if (user.phone == req.body.phone) {
            res.json({
                data: {
                    code: 502,
                    message: "请误输入原手机号"
                }
            })
        } else {
            createSmscode(req, res)
        }

    })
})
//修改手机号
router.post('/NewPhone', (req, res) => {
    Users.findOne({ _id: req.body._id }).then(user => {
        if (!user) {
            res.json({ data: { code: 502, message: "手机号错误", } })
        } else {
            if ((req.body.nowtime - user.sendtime) / 1000 > 60) {
                res.json({ data: { code: 501, message: "验证码已过期" } })
            } else {
                if (req.body.smscode == user.smscode) {
                    Users.updateOne({ _id: req.body._id }, {
                        $set: {
                            phone: req.body.phone
                        },
                    }).then(() => {
                        res.json({ data: { code: 200, message: "修改手机成功", } })
                    }).catch(() => {
                        res.json({ data: { code: 500, message: "修改手机失败", } })
                    })

                } else {
                    res.json({ data: { code: 500, message: "错误的验证码" } })
                }
            }
        }
    })
})
//验证
router.post('/IdentifyForgetPhone', (req, res) => {
    Users.findOne({ phone: req.body.phone }).then(user => {
        if (!user) {
            res.json({ data: { code: 502, message: "该手机号未被注册", } })
        }

        else {

            var smscode = ('000000' + Math.floor(Math.random() * 999999)).slice(-6);
            Users.updateOne({ phone: req.body.phone }, {
                $set: {
                    sendtime: req.body.sendtime,
                    smscode: smscode
                },
            }).then((p) => {
                console.log(p);
                res.json({ data: { code: 200, message: "获取验证码成功", smscode } })
            }).catch((err) => {
                console.log(err);
                res.json({ data: { code: 500, message: "获取验证码失败", } })
            })
        }
    })

})
//修改密码
router.post('/changePass', (req, res) => {
    let password = jsencrypt.decrypt(req.body.password)
    Users.updateOne({ phone: req.body.phone }, {
        $set: {
            password: password
        }
    }).then(() => {
        res.json({
            code: 200,
            message: "修改成功"
        })
    }).catch(() => {
        res.json({
            code: 500,
            message: "修改失败"
        })
    })
})

//增添地址
router.post('/addAddress', (req, res) => {
    let form = req.body.form
    let aid = ('000000' + Math.floor(Math.random() * 999999)).slice(-6) + Date.now();
    form.aid = aid;
    form.default = false;
    form.date = Date.now()
    form.current = true
    Users.updateOne({ _id: form.userid }, {
        $set: {
            'address.$[].current': false
        }
    }, {
        multi: true
    }).then(() => {
        Users.updateOne({ _id: form.userid }, {
            $addToSet: {
                address: form
            }
        }).then(() => {
            res.json({
                code: 200,
                message: '更新成功',
                data: form
            })
        }).catch(() => {
            res.json({
                code: 500,
                message: '更新失败'
            })
        })
    })

})

//删除地址
router.post('/deleteAddress', (req, res) => {
    Users.updateOne({ _id: req.body.userid }, {
        $pull: {
            address: { aid: req.body.aid }
        }
    }).then(() => {
        res.json({
            code: 200,
            message: "更新成功"
        })
    }).catch(() => {
        res.json({
            code: 500,
            message: '更新失败'
        })
    })
})

//更新地址
router.post('/updateAddress', (req, res) => {
    let form = req.body.form
    Users.updateOne({ _id: form.userid, 'address.aid': form.aid }, {
        $set: {
            'address.$': form,
        }
    }).then(() => {
        res.json({
            code: 200,
            message: '更新成功'
        })
    }).catch(err => {
        res.json({
            code: 500,
            message: '更新失败'
        })
    })
})

//更新地址状态
router.post('/updateCurrent', (req, res) => {

    if (req.body.current) {
        Users.updateOne({ _id: req.body.userid, 'address.aid': req.body.aid }, {
            $set: {
                'address.$.current': true
            }
        }).then(() => {
            res.json({
                code: 200,
                message: "修改成功",
            })
        }).catch(() => {
            res.json({
                code: 500,
                message: '更新失败'
            })
        })
    } else {
        Users.updateOne({ _id: req.body.userid, 'address.aid': req.body.aid }, {
            $set: {
                'address.$.current': false
            }
        }).then(() => {
            res.json({
                code: 200,
                message: "修改成功",
            })
        }).catch(() => {
            res.json({
                code: 500,
                message: '更新失败'
            })
        })
    }
})
//更新地址默认
router.post('/updateDefault', (req, res) => {
    if (req.body.default) {
        Users.updateOne({ _id: req.body.userid, 'address.aid': req.body.aid }, {
            $set: {
                'address.$.default': true
            }
        }).then(() => {
            res.json({
                code: 200,
                message: "修改成功",
            })
        }).catch(() => {
            res.json({
                code: 500,
                message: '更新失败'
            })
        })
    } else {
        Users.updateOne({ _id: req.body.userid, 'address.aid': req.body.aid }, {
            $set: {
                'address.$.default': false
            }
        }).then(() => {
            res.json({
                code: 200,
                message: "修改成功",
            })
        }).catch(() => {
            res.json({
                code: 500,
                message: '更新失败'
            })
        })
    }
})
//获取地址
router.get('/getAddress', (req, res) => {
    Users.findOne({ _id: req.query._id }).then(p => {
        res.json({
            code: 200,
            message: "获取地址成功",
            data: p.address
        })
    }).catch(() => {
        res.json({
            code: 500,
            message: '更新失败'
        })
    })
})
module.exports = router